package com.shqcjd.yunweiyanoperator.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.util.UIUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 忘记密码
 */
public class ForgetPwdActivity extends BaseActivity {


    @BindView(R.id.btn_finish)
    ImageView btn_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tl_phone)
    TextInputLayout tlPhone;
    @BindView(R.id.tv_get_code)
    TextView tvGetCode;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tl_code)
    TextInputLayout tlCode;
    @BindView(R.id.et_new_pwd)
    EditText etNewPwd;
    @BindView(R.id.tl_new_pwd)
    TextInputLayout tlNewPwd;
    @BindView(R.id.et_confirm_pwd)
    EditText etConfirmPwd;
    @BindView(R.id.tl_confirm_pwd)
    TextInputLayout tlConfirmPwd;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;

    private Context mContext;
    private String mCode="-1";
    private final int CODE_TIME = 1000;
    private int codeNum = 60;
    private String codePhone = "";//获取验证码的手机号

    private Handler codeHandler = new Handler();
    private Runnable codeRunnable = new Runnable() {
        @Override
        public void run() {
            tvGetCode.setText("还剩" + codeNum + "秒");
            if (codeNum == 1) {
                tvGetCode.setText("获取");
                codeHandler.removeCallbacks(codeRunnable);
            } else {
                codeNum--;
                codeHandler.postDelayed(codeRunnable, CODE_TIME);
            }
        }
    };

    @Override
    public void init() {
        super.init();
        mContext = this;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void initView() {
        tv_title.setText("找回密码");

        setTextChange(tlPhone, etPhone, "手机号不能为空");
        setTextChange(tlCode, etCode, "验证码不能为空");
        setTextChange(tlNewPwd, etNewPwd, "密码不能为空");
        setTextChange(tlConfirmPwd, etConfirmPwd, "确认密码不能为空");
    }

    private void setTextChange(TextInputLayout layout, EditText editText, String str) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                showInput(layout, editText, str);
            }
        });
    }

    private boolean showInput(TextInputLayout layout, EditText editText, String str) {
        if (TextUtils.isEmpty(editText.getText().toString().trim())) {
            layout.setError(str);
            return false;
        } else {
            layout.setError(null);
            layout.setErrorEnabled(false);

        }
        return true;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_forget_pwd;
    }


    @OnClick({R.id.btn_finish, R.id.tv_confirm, R.id.tv_get_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.tv_confirm:
                confirm();
                if(etCode.getText().toString().equals(mCode)){
                    if(etNewPwd.getText().toString().equals(etConfirmPwd.getText().toString())){
                        if(etConfirmPwd.getText().toString().trim().length()>=6){
                            if(codePhone.equals(etPhone.getText().toString().trim())){
                                personalRegisterHttp();
                            }else{
                                ToastUtils.showShort(mContext, "输入的手机号有误");
                            }
                        }else{
                            ToastUtils.showShort(mContext, "密码必须大于等于6位");
                        }
                    }else{
                        ToastUtils.showShort(mContext, "密码不一致");
                    }
                }else{
                    ToastUtils.showShort(mContext, "验证码有误");
                }
                break;
            case R.id.tv_get_code:
                if (tvGetCode.getText().toString().equals("获取")) {
                    if (UIUtils.isMobile(etPhone.getText().toString())) {
                        codeNum = 60;
                        codeHandler.postDelayed(codeRunnable, 1);
                        codePhone = etPhone.getText().toString();
                        getCodeHttp(etPhone.getText().toString().trim());
                    } else {
                        ToastUtils.showShort(mContext, "请输入正确的手机号");
                    }
                }
                break;
        }
    }

    private void personalRegisterHttp(){
        Map<String, String> map = new HashMap<>();
        map.put("password", etConfirmPwd.getText().toString().trim());
        map.put("phoneNumber", etPhone.getText().toString().trim());
        map.put("verificationCode", mCode);
        String json =  new JSONObject(map).toString();
        ApiService.forgetPassword(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "密码修改成功");
                            Intent it = new Intent(mContext, LoginActivity.class);
                            it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(it);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getCodeHttp(String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("phoneNumber", phone);
        String json =  new JSONObject(map).toString();
        ApiService.getCode(json)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<String>>() {

                    @Override
                    public void _onNext(ResponseData<String> retData) {
                        if (retData != null && retData.retCode == 10000) {
                            mCode = retData.data;
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void confirm() {
        if (!showInput(tlPhone, etPhone, "手机号不能为空")&&
                !showInput(tlCode, etCode, "验证码不能为空")&&
                !showInput(tlNewPwd, etNewPwd, "密码不能为空")&&
                !showInput(tlConfirmPwd, etConfirmPwd, "确认密码不能为空")) {
            return;
        }

    }

}
